<?php
/**
 * 发票控制器
 * User: guojing
 * Date: 2020/4/7
 * Time: 23:13
 */
namespace app\api\controller;


use app\api\model\RechargeOffline;
use app\api\model\UserInvoice;
use app\common\controller\Api;
use think\Cookie;
use think\Db;
use app\api\model\Invoice as InvoiceModel;
use app\api\model\User as UserModel;

class Invoice extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';

    /**
     * 搜索发票
     */
    public function searchInvoice()
    {
        $userId = UserModel::getCurrUid($this->request->param('user_id', 0));
        if ($userId <= 0) {
            $this->success('success', []);
        }

        //发票抬头
        $invoiceRise = $this->request->post('invoice_rise', '');
        if (!$invoiceRise) {    //不输入抬头信息，返回当前登录用户曾经输入的所有抬头信息
            if ($userId <= 0) {
                $this->success('success', []);
            } else {
                $list = UserInvoice::selListByCondition(['uid' => $userId]);
            }
        } else {
            $list = UserInvoice::selListByCondition(['uid' => $userId,'invoice_rise' => ['like', $invoiceRise.'%']]);
        }

        if ($list) {
            $this->success('success', $list);
        } else {
            $this->success('success', []);
        }
    }

    /**
     *  提交发票申请
     */
    public function apply()
    {
        $userId = UserModel::getCurrUid($this->request->param('user_id', 0));
        if ($userId <= 0) {
            $this->error('请重新登录', [],401);
        }
        $posts = $this->request->post();
        $invoiceType = $this->request->post('invoice_type', 1, 'intval');
        $invoiceRise = $this->request->post('invoice_rise', '');
        $dutyParagraph = $this->request->post('duty_paragraph', '');
        $unitAddress = $this->request->post('unit_address', '');
        $contact = $this->request->post('contact', '');
        $depositBank = isset($posts['deposit_bank']) ? trim($posts['deposit_bank']) : '';
        $bankAccount = isset($posts['bank_account']) ? trim($posts['bank_account']) : '';
        $icontents = $this->request->post('icontents', '');
        $iremarks = $this->request->post('iremarks', '');
        $amount = $this->request->post('amount', 0, 'floatval');
        $amount = (float)(sprintf('%.2f', $amount));
        if ($amount <= 0) {
            $this->error(__('开票金额为必要信息，不能留空！'));
        }
        if (!$invoiceRise) {
            $this->error(__('发票抬头为必要信息，不能留空！'));
        }
        if (!$dutyParagraph) {
            $this->error(__('税号为必要信息，不能留空！'));
        }
        if ($invoiceType == 2) {    //专票
            if (!$unitAddress) {
                $this->error(__('单位地址为必要信息，不能留空！'));
            }
            if (!$contact) {
                $this->error(__('电话号码为必要信息，不能留空！'));
            }
            if (!$depositBank) {
                $this->error(__('开户银行为必要信息，不能留空！'));
            }
            if (!$bankAccount) {
                $this->error(__('银行账号为必要信息，不能留空！'));
            }
            if (!$icontents) {
                $this->error(__('发票内容为必要信息，不能留空！'));
            }
        }

        //检测已开的发票总金额
        $totalInvoicePrice = InvoiceModel::sumInvoicePrice(['uid' => $userId]);
        //检测已充值的总金额
        $totalRechargePrice = RechargeOffline::sumRechargePrice(['send_uid' => $userId, 'apply_status' => 2]);
        if (($totalInvoicePrice + $amount) > $totalRechargePrice) {
            $this->error(__("总充值金额为{$totalRechargePrice}元，本次只能申请开票金额为" . ($totalRechargePrice - $totalInvoicePrice) . "元!"));
        }

        // 获取用户审核中的发票信息
        $invoice = InvoiceModel::findInfoByCondition(['uid' => $userId, 'apply_status' => ['in', [0,1]]]);

        $data = [
            'invoice_type' => $invoiceType,
            'invoice_rise' => $invoiceRise,
            'duty_paragraph' => $dutyParagraph,
            'unit_address' => $unitAddress,
            'contact' => $contact,
            'deposit_bank' => $depositBank,
            'bank_account' => $bankAccount,
            'icontents' => $icontents,
            'iremarks' => $iremarks,
            'uid' => $userId,
            'amount' => $amount
        ];

        if ($invoice) { //如果有发票信息，修改发票的相关信息
            InvoiceModel::saveData($invoice['id'], $data);
        } else {
            $invoice = InvoiceModel::addRecord($data);
            if (!$invoice) {
                $this->error(__('提交申请失败！'));
            }
            unset($data);
        }

        //检测抬头记录是否已存在
        $invoiceData = [
            'invoice_rise' => $invoiceRise,
            'duty_paragraph' => $dutyParagraph,
            'unit_address' => $unitAddress,
            'contact' => $contact,
            'deposit_bank' => $depositBank,
            'bank_account' => $bankAccount,
            'uid' => $userId
        ];
        $userInvoice = UserInvoice::findInfoByCondition(['uid' => $userId, 'invoice_rise' => $invoiceRise]);
        if (!$userInvoice) {
            UserInvoice::addRecord($invoiceData);
        } else {
            UserInvoice::saveData($userInvoice['id'], $invoiceData);
        }

        $this->success('success', []);
    }

}